<template>
  <dragSize
    v-for="item in dialogList"
    :key="item.RID"
    :kvm="item"
    :drag-min-height="500"
    :drag-min-width="740"
    :p-index="item.RID"
    :is-show="true"
    :z-index="item.zIndex || 10000"
    @selectItem="topDialog"
    @openNew="openFunc"
    @close="beforeClose"
  >
    <div
      class="dialog_content"
      :id="item.RID"
      :style="{ zIndex: item.zIndex || 10000 }"
    >
      <div v-loading="radioMap[item.RID].loading" style="height: 100%">
        <div class="terminalOption space-x-1 flex flex-row">
          <div style="color: #444">
            是否只读:
            <el-switch
              v-model="radioMap[item.RID].read"
              @change="changeVirtual(item)"
            />
          </div>
          <!-- <div>
            是否开启录屏:
            <el-switch
              v-model="radioMap[item.RID].record"
              @change="changeVirtual(item)"
            />
          </div> -->
        </div>
        <div class="virtualiframe">
          <div
            :class="['iframeMain', radioMap[item.RID].read ? 'readonly' : '']"
          >
            <iframe
              :id="'Terminal' + item.RID"
              :src="item.uri ? origin + '/console/#/client/' + item.uri : null"
              width="100%"
              height="100%"
            />
          </div>
          <div
            :class="['mask', currentRID === item.RID ? 'active' : '']"
            @click="topDialog(item)"
          />
        </div>
      </div>
    </div>
  </dragSize>
</template>
<script setup>
import { nextTick, ref, defineExpose } from 'vue';
import { getVirtual } from '@/api/topo/simulationApi/topo.js';
import dragSize from './dragSize.vue';
const emit = defineEmits(['closeDialog', 'topDialog']);
const props = defineProps({
  dialogList: {
    default: function () {
      return [];
    },
    type: Array,
  },
});
const topDialog = item => {
  currentRID.value = item?.RID;
  emit('topDialog', item);
};
const beforeClose = item => {
  closeFunc(item);
  emit('closeDialog', item);
};
const origin = ref(null);
const mode = import.meta.env.MODE;
origin.value =
  mode === 'development' ? 'https://172.17.0.29' : window.location.origin;
//保存read、loading等信息
const radioMap = ref({});

const currentRID = ref();

//控制台
const changeVirtual = async arg => {
  radioMap.value[arg.RID].loading = true;
  getVirtual(arg.id, arg.RID, {
    read: radioMap.value[arg.RID].read,
    record: radioMap.value[arg.RID].record,
  }).then(async res => {
    if (!(res instanceof Error)) {
      const {
        data: { token },
      } = res;
      await setIfameInfo(arg, token);
      radioMap.value[arg.RID].loading = false;
    }
  });
};
/**
 * 销毁iframe，释放iframe所占用的内存。
 * @param iframe 需要销毁的iframe id
 */
function destroyIframe(iframeID) {
  var iframe = document.getElementById(iframeID);

  //把iframe指向空白页面，这样可以释放大部分内存。
  iframe.src = 'about:blank';

  try {
    iframe.contentWindow.document.write('');
    iframe.contentWindow.document.clear();
  } catch (e) {}

  //把iframe从页面移除
  iframe.parentNode.removeChild(iframe);
}
function focusFunc(item) {
  let iframe = document.getElementById('Terminal' + item.RID);
  if (iframe && iframe.contentWindow && !radioMap.value[item.RID].read) {
    // 在此处执行方法加载完毕后的代码
    setTimeout(() => {
      iframe.focus();
    });
  }
}
function closeFunc(item) {
  let iframe = document.getElementById('Terminal' + item.RID);
  var iframeDoc = iframe.contentDocument || iframe.contentWindow.top.document;
  iframe && iframe.removeEventListener('load', focusFunc(item));
  iframeDoc.removeEventListener('click', function () {
    topDialog(item);
    focusFunc(item);
  });
  destroyIframe('Terminal' + item.RID);
  delete radioMap.value[item.RID];
}
const openFunc = async item => {
  radioMap.value[item.RID] = {
    read: false,
    record: false,
    loading: true,
  };
  await setIfameInfo(item, item.token);
};
function setIfameInfo(item, token) {
  nextTick(() => {
    const iframeWindow = document.getElementById(
      'Terminal' + item.RID,
    ).contentWindow;
    iframeWindow.localStorage.setItem(
      'GUAC_AUTH',
      JSON.stringify({ authToken: token }),
    );
    let iframe = document.getElementById('Terminal' + item.RID);
    iframe.onload = function () {
      var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
      iframeDoc.addEventListener('click', function () {
        topDialog(item);
        focusFunc(item);
      });
    };
    iframe && iframe.addEventListener('load', focusFunc(item));
    currentRID.value = item?.RID;
    if (radioMap.value[item.RID].read) {
      iframeWindow.addEventListener('keydown', readonlyDocument);
      iframeWindow.addEventListener('mousedown', readonlyDocument);
    } else {
      iframeWindow.removeEventListener('keydown', readonlyDocument);
      iframeWindow.removeEventListener('mousedown', readonlyDocument);
      focusFunc(item);
    }
    radioMap.value[item.RID].loading = false;
  });
  function readonlyDocument(event) {
    event && event.preventDefault();
  }
}
defineExpose({
  openFunc,
  focusFunc,
});
</script>

<style lang="scss" scoped>
.dialog_content {
  width: 100%;
  height: 100%;
}
.virtualiframe {
  padding: unset;
  border-radius: unset;
  width: 100%;
  height: calc(100% - 35px);
  overflow: auto;
  position: relative;
  .iframeMain {
    width: 100%;
    height: 100%;
    &.readonly {
      iframe {
        pointer-events: none;
        -moz-user-select: none; /*火狐*/
        -webkit-user-select: none; /*webkit浏览器*/
        -ms-user-select: none; /*IE10*/
        //-khtml-user-select: none; /*早期浏览器*/
        user-select: none;
      }
    }
  }

  .mask {
    width: calc(100% - 2px);
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    &.active {
      height: 0;
    }
  }
}
</style>
